package com.study.ssm.annotation02.yaml;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import org.springframework.util.StringUtils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Objects;
import java.util.Properties;

/**
 * @author zhoujunlin
 * @date 2023年07月27日 23:08
 * @desc
 */
public class YamlPropertySourceFactory implements PropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(resource.getResource());

        Properties properties = factory.getObject();
        if (Objects.nonNull(properties)) {
            if (StringUtils.isEmpty(name)) {
                name = "customize";
            }
            return new PropertiesPropertySource(name, properties);
        } else {
            throw new FileNotFoundException("Could not load YAML file: " + resource.getResource().getFilename());
        }
    }

}
